package com.pmdb.util;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import com.pmdb.core.data.Language;

public class LanguageUtil {

   private static final Logger LOG = Logger.getLogger(LanguageUtil.class);
   
   private static final int NUM_ITEMS = 2;

   private static final String[] languages = new String[] {
      "English",
      "French"};

   private static int languageIdx = -1;
   private static List<Language> items = new ArrayList<Language>();
   private EntityManager em = null;

   public LanguageUtil(EntityManager em) {
      this.em = em;
   }

   public void generateLanguages() {
     for (int i = 0; i < NUM_ITEMS; ++i) {
       items.add(createLanguage());
     }
   }

   public Language getLanguage(int index) {
     if (index >= items.size()) {
       return null;
     }
     return items.get(index);
   }

   public int getLanguageCount() {
     return items.size();
   }

   private Language createLanguage() {
     languageIdx++;
     return new Language(languages[languageIdx]);
   }

   private Language createLanguage(String name) {
     Language newLanguage = new Language(name);
     em.persist(newLanguage);
     return newLanguage;
   }

   public Language findLanguageByName(String name) {
      Query languageByName = em.createQuery("from Language l where l.name like :name");
      languageByName.setParameter("name", name);

      if(languageByName.getResultList().size() == 0) {
         LOG.debug("Not Found: " + name);
         return null;
      }
      else {
         LOG.debug("Found: " + name);
         return (Language)languageByName.getSingleResult();
      }
   }

   public Language findOrCreate(String name) {
      Language language = this.findLanguageByName(name);
      if(language == null) {
         language = this.createLanguage(name);
         LOG.debug("Language: " + name + " not found! (created)");
      }
      return language;
   }
}
